import numpy as np
import matplotlib.pyplot as plt

def model(x,theta):
    return np.dot(x,theta)

def cost(h,y):
    return 0.5*np.mean((h-y)**2)

def grad(x,y,alpha=0.1,iter0=2000):
    m,n=x.shape
    theta=np.zeros(n)
    J=np.zeros(iter0)
    for i in range(iter0):
        h=model(x,theta)
        J[i]=cost(h,y)
        dt=1/m*x.T.dot(h-y)
        theta-=alpha*dt
    return h,J,theta

def score(h,y):
    u=np.mean((h-y)**2)
    miu=np.mean(y)
    v=np.mean((y-miu)**2)
    return 1-u/v

if __name__ == '__main__':
    data=np.loadtxt('ex1data2.txt',delimiter=',')
    x=data[:,:-1]
    y=data[:,-1]

    miu=np.mean(x,axis=0)
    sigma=np.std(x,axis=0)
    x=(x-miu)/sigma

    np.random.seed(666)
    a=np.random.permutation(len(x))
    x=x[a]
    y=y[a]

    X=np.c_[np.ones(len(x)),x]

    num=int(0.7*len(x))
    train_x,test_x=np.split(X,[num,])
    train_y,test_y=np.split(y,[num,])

    train_h,J,theta=grad(train_x,train_y)
    plt.plot(J)
    plt.show()

    test_h=model(test_x,theta)

    print(score(test_h,test_y))
